package com.qiandw.security.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qiandw.security.entity.UserDetailImpl;
import com.qiandw.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.servlet.ServletException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author coxx
 */
@Slf4j
public class LoginSuccessHandle extends SavedRequestAwareAuthenticationSuccessHandler {

    private DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Override
    public void onAuthenticationSuccess(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Authentication authentication) throws ServletException, IOException, ServletException {
        UserDetailImpl userDetails = ((UserDetailImpl) authentication.getPrincipal());
        log.info(String.format("用户：$1%s, 权限列表：$2%s, 登陆时间：$3%s, 登陆IP：$4%s", userDetails.getUsername(), JSON.toJSONString(userDetails.getAuthorities(),
                SerializerFeature.NotWriteDefaultValue), dataFormat.format(new Date()), IPUtils.getIPAddress(request)));
        super.onAuthenticationSuccess(request, response, authentication);
    }
}
